package com.smile.cloud.nettyService.channelInitializer;

import com.smile.cloud.nettyService.handler.ServerHeartHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author yangzj
 * @date 2021-09-03 09:41:36
 **/
@Component
public class ServerChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Autowired
    private ServerHeartHandler serverHeartHandler;

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        //websocket协议本身是基于Http协议的，所以需要Http解码器
        pipeline.addLast(new HttpServerCodec());
        //以块的方式来写的处理器
        pipeline.addLast(new ChunkedWriteHandler());
        //netty是基于分段请求的，HttpObjectAggregator的作用是将请求分段再聚合,参数是聚合字节的最大长度
        pipeline.addLast(new HttpObjectAggregator(1024 * 1024));
        //这个是websocket的handler，是netty提供的，也可以自定义，建议就用默认的
        pipeline.addLast(new WebSocketServerProtocolHandler("/", null, true, 65535));
        //自定义的handler，处理服务端传来的消息
        pipeline.addLast(serverHeartHandler);
    }
}
